<?php

class Core_Component_System_Business_Localize {

    public function writeLanguageFile($key, $content, $langCode = NULL){
        $langCode = is_null($langCode)? $GLOBALS[RC]->getLanguageCode(): $langCode;
        $arr = explode('.', $key);
        $firstKey = array_shift($arr);
        $lastKey = array_pop($arr);
        if(file_exists(DP_LANG.$langCode.DS.$firstKey.'.yml')){
            $lang = Soul_Util_Yaml::parseFile(DP_LANG.$langCode.DS.$firstKey.'.yml');
            $item = &$lang;
            foreach($arr as $key){
                if(!isset($lang[$key])){
                    $item[$key] = array();
                }
                $item = &$item[$key];
            }
            if(!isset($item[$lastKey]) || $item[$lastKey] != $content){
                $item[$lastKey] = $content;
                $data = Soul_Util_Yaml::dump($lang);
                file_put_contents(DP_LANG.$langCode.DS.$firstKey.'.yml', $data);
            }
        }
    }
    
    public function replaceLangTag($content){
        $result = $content;
        if(preg_match_all('/<\{lang\s+"([a-z0-9\.\-\_]+)"\}>/i', $content, $matches)){
            $lang = $GLOBALS[RC]->getLanguage();
            $len = count($matches[0]);
            for($i = 0; $i < $len; $i++){
               $text = $lang->__($matches[1][$i]);
               if(is_null($text)){
                   $text = $matches[1][$i];
               }
               $result = str_replace($matches[0][$i], $text, $result);
            }
        }
        return $result;
    }
}